package com.easycoding.ums.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.easycoding.framework.exception.BussinessException;
import com.easycoding.framework.exception.SecurityException;
import com.easycoding.framework.util.MD5;
import com.easycoding.ums.enumcode.AccountStatus;
import com.easycoding.ums.exception.UserNoExistsException;
import com.easycoding.ums.exception.UserPauseException;
import com.easycoding.ums.exception.UserStopException;
import com.easycoding.ums.exception.VerifyFailureException;
import com.easycoding.ums.system.bo.UserTicket;
import com.easycoding.ums.system.entity.Permission;
import com.easycoding.ums.system.entity.Role;
import com.easycoding.ums.system.entity.RolePermission;
import com.easycoding.ums.system.entity.User;
import com.easycoding.ums.system.entity.UserRole;
import com.easycoding.ums.system.repository.UserRepository;
import com.easycoding.ums.system.service.UserService;

/**
 * 用户服务实现类
 * @author Wangjk
 * @Version 1.0
 * @Date 2013-4-1
 */
@Service("umsUserService")
public class UserServiceImpl implements UserService{

	/**
	 * 用户信息Repository
	 */
	@Resource
	private UserRepository userRepository;
	
	/* (non-Javadoc)
	 * @see UserService#insertUser(User user)
	 */
	public void insertUser(User user) {
		User existsUser = this.userRepository.findByAccount(user.getAccount());
		if(existsUser != null){
			throw new BussinessException("账号:"+user.getAccount()+"已经被使用！");
		}
		else{
			/**
			 * MD5密码加密
			 */
			MD5 md5 = new MD5();
			user.setPassword(md5.getMD5Hash(user.getPassword()));
			if(user.getAccountStatus() == null)
				user.setAccountStatus(AccountStatus.OPEN.getCode());
			user.setRegTime(new Date());
			user = this.userRepository.save(user);
			//设置idtree
			//子账号
			if(user.getParentId() != null){
				User parent = this.userRepository.findOne(user.getParentId());
				if(parent != null){
					String idtree = parent.getIdtree() + "," +user.getId();
					user.setIdtree(idtree);
					this.userRepository.save(user);
				}
			}//父账号
			else{
				user.setIdtree(String.valueOf(user.getId()));
				this.userRepository.save(user);
			}
		}
	}

	/* (non-Javadoc)
	 * @see UserService#updateUser(User user)
	 */
	public void updateUser(User user) {
		this.userRepository.save(user);
	}

	/* (non-Javadoc)
	 * @see UserService#deleteUserById(Long id)
	 */
	public void deleteUserById(Long id) {
		this.userRepository.delete(id);
	}

	/* (non-Javadoc)
	 * @see UserService#stopUser(Long id)
	 */
	public void stopUser(Long id) {
		User user = this.userRepository.findOne(id);
		if(user == null){
			throw new BussinessException("用户不存在!");
		}
		else{
			user.setAccountStatus(AccountStatus.CLOSE.getCode());
			this.userRepository.save(user);
		}
	}

	/* (non-Javadoc)
	 * @see UserService#resumeUser(Long id)
	 */
	public void resumeUser(Long id) {
		User user = this.userRepository.findOne(id);
		if(user == null){
			throw new BussinessException("用户不存在!");
		}
		else{
			user.setAccountStatus(AccountStatus.OPEN.getCode());
			this.userRepository.save(user);
		}
	}

	/* (non-Javadoc)
	 * @see UserService#verifyUser(String account , String password)
	 */
	public User verifyUser(String account , String password) throws SecurityException{
		User user = this.userRepository.findByAccount(account);
		if(user == null){
			throw new UserNoExistsException();
		}
		else if(user.getAccountStatus() == AccountStatus.CLOSE.getCode()){
			throw new UserStopException();
		}
		else if(user.getAccountStatus() == AccountStatus.PAUSE.getCode()){
			throw new UserPauseException();
		}
		else{
			/**
			 * MD5密码加密
			 */
			MD5 md5 = new MD5();
			password = md5.getMD5Hash(password);
			if(StringUtils.equals(password, user.getPassword()))
				return user;
			else{
				throw new VerifyFailureException();
			}
		}
		
	}

	/* (non-Javadoc)
	 * @see UserService#findByAccount(String account)
	 */
	public User findByAccount(String account) {
		return this.userRepository.findByAccount(account);
	}

	/* (non-Javadoc)
	 * @see UserService#pauseUser(Long id)
	 */
	public void pauseUser(Long id) {
		User user = this.userRepository.findOne(id);
		if(user == null){
			throw new BussinessException("用户不存在!");
		}
		else{
			user.setAccountStatus(AccountStatus.PAUSE.getCode());
			this.userRepository.save(user);
		}
		
	}

	/* (non-Javadoc)
	 * @see UserService#findByUserAccount(String account)
	 */
	public UserTicket findByUserAccount(String account) {
		//查找用户
		User user = this.findByAccount(account);
		if(user != null){
			UserTicket userTicket = new UserTicket();
			userTicket.setUser(user);
			List<Role> roles = new ArrayList<Role>();
			List<Permission> permissions = new ArrayList<Permission>();
			//角色
			if(user.getUserRoles() != null && !user.getUserRoles().isEmpty()){
				for(UserRole userRole : user.getUserRoles()){
					if(userRole != null && userRole.getRole() != null){
						Role role = userRole.getRole();
						roles.add(role);
						//权限
						if( role.getUserPermissions() != null && !role.getUserPermissions().isEmpty()){
							for(RolePermission rolePermission : role.getUserPermissions()){
								if(rolePermission != null && rolePermission.getPermission() != null){
									permissions.add(rolePermission.getPermission());
								}
								
							}
						}
					}
				}
			}
			userTicket.setRoles(roles);
			userTicket.setPermissions(permissions);
			return userTicket;
		}
		return
			null;
	}

	/* (non-Javadoc)
	 * @see UserService#findById(Long id)
	 */
	public User findById(Long id) {
		return this.userRepository.findOne(id);
	}

	/* (non-Javadoc)
	 * @see UserService#findChildren(Long id)
	 */
	@Override
	public List<User> findChildren(Long id) {
		return this.userRepository.findByParentIdAndIsChildOrderByUpdTimeDesc(id, false);
	}
}
